package com.sky.controller;

import com.sky.entity.FormUserMaterial;
import com.sky.result.Result;
import com.sky.service.FormUserMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/formUserMateri")
@Api(tags = "用户表单材料管理接口")
@Slf4j
public class FormUserMaterialController {

    @Autowired
    private FormUserMaterialService formUserMaterialService;

    @PostMapping("/upload")
    @ApiOperation("上传表单数据")
    public Result uploadFormData(@RequestBody List<FormUserMaterial> formDataList) {
        try {
            formUserMaterialService.saveFormDataBatch(formDataList);
            return Result.success();
        } catch (Exception e) {
            log.error("上传表单数据失败：", e);
            return Result.error("上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/vue/{orderId}")
    @ApiOperation("获取表单数据")
    public Result getFormData(@PathVariable String orderId) {
        try {
            List<FormUserMaterial> formDataList = formUserMaterialService.getFormDataByOrderId(orderId);
            // 将数据转换为前端需要的格式
            Map<String, List<FormUserMaterial>> groupedData = formDataList.stream()
                    .collect(Collectors.groupingBy(FormUserMaterial::getMaterialType));
            
            List<Map<String, Object>> result = new ArrayList<>();
            for (Map.Entry<String, List<FormUserMaterial>> entry : groupedData.entrySet()) {
                Map<String, Object> typeData = new HashMap<>();
                typeData.put("type", entry.getKey());
                
                Map<String, String> fields = new HashMap<>();
                for (FormUserMaterial material : entry.getValue()) {
                    fields.put(material.getFieldName(), material.getFieldValue());
                }
                
                typeData.put("fields", fields);
                typeData.put("material_category", entry.getValue().get(0).getMaterialCategory());
                result.add(typeData);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取表单数据失败：", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
}